<?php

namespace app\mobile\controller;

class Research extends Base
{
    //前置方法
    protected $beforeActionList = [
        'rquestion' => ['only' => 'detailed'],
        'right' => ['only' => 'index,detailed'],

    ];

    public function rquestion()
    {
        $id = $this->request->param('id');

        $aa = cache('rquestion'.$id . cookie('think_var'));

        if(empty($aa)){

            $an = db('research_result')->where('rid',$id)->select();

            foreach ($an as $k => $value) {
                $answer = json_decode($value['content']);
                foreach ($answer as $ki => $va) {
                    $aa[$k][$ki]['question'] = db('research_question')->where(array('id' => $ki))->value('name');
                    $aa[$k][$ki]['answer'] = $va;
                }
            }
            cache('rquestion'.$id . cookie('think_var'),$aa);

        }

        $list = cache('question'.$id . cookie('think_var'));

        if(empty($list)) {
            $rqdata = db('Research_question')->where(array('rid' => $id))->order('id asc')->select();
            $useqids = $list = array();
            foreach ($rqdata as $v) {
                $useqids[] = $v['id'];
                $answerobj = db('Research_answer')->where(array('qid' => $v['id']))->order('id asc')->select();
                $v['answer'] = $answerobj;
                $v['rowspan'] = count($v['answer']);
                $list[] = $v;
            }
            cache('question'.$id . cookie('think_var'),$list);

        }

        $this->assign([
            'list'=>$list,
            'aa'=>$aa,
            ]
        );

    }


    /**
     * 保存调研结果
     */
    public function saveresearch()
    {

        $oo = $this->request->param();
        $dateline = db('research')->where('id', $oo['id'])->value('dateline');
       if($dateline<time()){
           return ajax_info('已经超过时间','u');
       }

        $o = db('research_result')->where('rid', $oo['id'])->find();
        if ($o) {
            return ajax_info('已经提交过', 'u');
        }


        if (empty($oo['oid'])) {
//            $this->error('选择');
            return ajax_info('选择');

        }

        $oo['center'] = !empty($oo['center'])?$oo['center']:'';
        $data = array(
            'rid' => $oo['id'],
            'qid' => $oo['id'],
            'content' => json_encode($oo['center']),
        );
        db('research_result')->insert($data);


        foreach ($oo['oid'] as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $vv) {
                    $value[] = $vv;
                }
            } else {
                $value[] = $v;
            }
        }
        $date = implode(',', $value);

        db('research')->where('id', $this->request->param('id'))->setInc('nums');
        db('research_answer')->where('id', 'in', $date)->setInc('nums');

//$this->success('投票成功');
        return ajax_info('投票成功', 'u');


    }

}
